/*
 *
 *
 */

#include "gkt_debug.h"
#include "gkt_hmac.h"

#define TOTP_TIME_MAXSIZE	8

//static uint8_t s_totp_key[] = {
//	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
//	0x00, 0x00, 0xAB, 0x54, 0xA9, 0x8C, 0xEB, 0x1F, 0x0A, 0xD2

//	0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x30,
//	0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x30,
//	0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x30,
//	0x31, 0x32

//	0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38
//};

int gkt_totp_generate(
		uint32_t time_steps,
		const uint8_t *key, uint32_t key_size,
		char *digital_totp, uint32_t totp_digits)
{
	uint8_t time_step_hex[TOTP_TIME_MAXSIZE];
	uint8_t hash[GKT_CRYPTO_SHA1_DIGEST_BYTES];
	uint32_t offset, binary, i;
	int retval;

	for (i = 0; i < TOTP_TIME_MAXSIZE; i++) {
		time_step_hex[TOTP_TIME_MAXSIZE - 1 - i] = (uint8_t)time_steps;
		time_steps >>= 8;
	}

	retval = gkt_hmac(GKT_HMAC_SHA1,
				key, key_size, 
				time_step_hex, TOTP_TIME_MAXSIZE, 
				hash);
	if (GKT_SUCCESS == retval) {
		offset = hash[GKT_CRYPTO_SHA1_DIGEST_BYTES - 1] & 0x0f;
		binary = gkt_fetch_be32(&hash[offset]) & 0x7fffffff;
		for (i = totp_digits; i > 0; ) {
			digital_totp[--i] = '0' + (binary % 10);
			binary /= 10;
		}
	}

	return retval;
}

